<?php

namespace App\Repositories\Goods;

use Carbon\Carbon;
use Illuminate\Support\Facades\Cache;
use Prettus\Repository\Eloquent\BaseRepository;
use Prettus\Repository\Criteria\RequestCriteria;
use App\Repositories\Goods\GoodsPresellTimeRepository;
use App\Models\Goods\GoodsPresellTime;
use App\Validators\Goods\GoodsPresellTimeValidator;

/**
 * Class GoodsPresellTimeRepositoryEloquent.
 *
 * @package namespace App\Repositories\Goods;
 */
class GoodsPresellTimeRepositoryEloquent extends BaseRepository implements GoodsPresellTimeRepository
{
    /**
     * Specify Model class name
     *
     * @return string
     */
    public function model()
    {
        return GoodsPresellTime::class;
    }

    

    /**
     * Boot up the repository, pushing criteria
     */
    public function boot()
    {
        $this->pushCriteria(app(RequestCriteria::class));
    }

    /**
     * 检查该订单商品是否在发货时间分段内
     * @author Jerry
     * @param int $goodsId
     * @param string $payTime
     * @return mixed
     */
    public function findGoodsPreSaleTimeByGoodsId(int $goodsId, string  $payTime)
    {
        $where = [
            'goods_id'      =>  $goodsId,
            'delivery_time' =>  $payTime,
        ];

        $expiresAt = Carbon::now()->addDay(1);

        return Cache::remember("goods:GoodsPreSaleTime", $expiresAt, function () use ($where) {
            return $this->orderBy('delivery_time', 'asc')->orderBy('endval', 'desc')->findWhere($where)->first();
        });
    }

    /**
     * 检查预售商品是否设置发货配送时间
     * @author Jerry
     * @param int $goodsId
     * @return mixed
     */
    public function findGoodsShippingPreSaleTimeCountByGoodsId(int $goodsId)
    {
        $where = [
            'goods_id'  =>  $goodsId,
        ];

        $expiresAt = Carbon::now()->addDay(1);

        return Cache::remember("goods:ShippingPreSaleTimeCount", $expiresAt, function () use ($where) {
            return $this->findWhere($where)->count();
        });
    }
    
}
